<template>
  <div class="employee_detail  form_detail_page">
    <one-title :title="$route.query.id ? '人员详情' : '人员新增'" @refreshData="refresh"></one-title>
    <div v-loading="isLoading" class="fixed_top_56">
      <el-form ref="listForm" @submit.native.prevent :model="detailData" :rules="rules" v-if="!isEmpty&&!isLoading">
        <two-title title="基本信息"></two-title>
        <div class="from_panel">
          <div class="form_col">
            <el-form-item class="form_item" label="人员编号:" prop="number">
              <div class="input_wapper">
                <el-input
                  placeholder="请输入人员编号"
                  v-model.trim="detailData.number"
                  disabled
                  size="small"
                  clearable>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="姓名:" prop="name">
              <div class="input_wapper">
                <el-input
                  placeholder="请输入姓名"
                  v-model.trim="detailData.name"
                  disabled
                  size="small"
                  clearable>
                </el-input>
              </div>
            </el-form-item>
          </div>
          <div class="form_col">
            <el-form-item class="form_item" label="性别:" prop="genderId">
              <div class="input_wapper">
                <el-select v-model="detailData.genderId" disabled size="small" filterable placeholder="">
                  <el-option
                    v-for="item in genderType"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="出生日期:" prop="birthday">
              <div class="input_wapper">
                <el-date-picker
                  :clearable="false"
                  v-model="detailData.birthday"
                  type="date"
                  disabled
                  placeholder=""
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  size="small"
                  :picker-options="getPickerOptions1(detailData.workingDate)">
                </el-date-picker>
              </div>
            </el-form-item>
          </div>
        </div>
        <two-title title="班组信息"></two-title>
        <div class="from_panel">
          <div class="form_col">
            <el-form-item class="form_item" label="工厂名称:" prop="factoryId">
              <div class="input_wapper">
                <el-select filterable disabled placeholder="" @change="factorySelect" size="small" v-model="detailData.factoryId">
                  <el-option
                    v-for="item in treeList"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="车间名称:" prop="workshopId">
              <div class="input_wapper">
                <el-select filterable disabled placeholder="" size="small" @change="workshopSelect" v-model="detailData.workshopId">
                  <el-option
                    v-for="item in workshop"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="班组名称:" prop="workgroupId">
              <div class="input_wapper">
                <el-select
                  filterable
                  v-model="detailData.workgroupId"
                  size="small"
                  placeholder="请选择班组名称">
                  <el-option
                    v-for="item in workgroup"
                    :key="item.id"
                    :label="item.text"
                    :value="item.id">
                  </el-option>
                </el-select>
              </div>
            </el-form-item>
          </div>
          <div class="form_col">
            <el-form-item class="form_item" label="参工时间:" prop="workingDate">
              <div class="input_wapper">
                <p class="work_time_date">
                  <el-date-picker
                    :clearable="false"
                    v-model="detailData.workingDate"
                    type="date"
                    placeholder="选择日期"
                    format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd HH:mm:ss"
                    size="small"
                    :picker-options="getPickerOptions2(detailData.birthday)">
                  </el-date-picker>
                </p>
                <span class="work_time_year" v-text="workTime"></span>
              </div>
            </el-form-item>
          </div>
        </div>
        <two-title title="其他信息"></two-title>
        <div class="from_panel">
          <div class="form_col">
            <el-form-item class="form_item" label="电话:" prop="phone">
              <div class="input_wapper">
                <el-input
                  placeholder="请输入电话"
                  v-model.trim="detailData.phone"
                  size="small"
                  disabled
                  clearable>
                </el-input>
              </div>
            </el-form-item>
            <el-form-item class="form_item" label="邮箱:" prop="email">
              <div class="input_wapper">
                <el-input
                  placeholder="请输入邮箱"
                  disabled
                  v-model.trim="detailData.email"
                  size="small"
                  clearable>
                </el-input>
              </div>
            </el-form-item>
            <div class="form_item">
              <label></label>
              <div class="input_wapper mes_btn">
                <el-button type="primary" native-type="submit" @click="save">保存</el-button>
                <el-button @click="cancel">取消</el-button>
              </div>
            </div>
          </div>
          <div class="form_col">
            <el-form-item class="form_item" label="备注:" prop="remarks">
              <div class="input_wapper text_area">
                <el-input type="textarea"
                          :autosize="{ minRows: 2, maxRows: 4}"
                          placeholder="请输入内容"
                          v-model="detailData.remarks"
                          maxlength="255"></el-input>
                <span class="text_length">{{detailData.remarks ? detailData.remarks.length : 0}}/255</span>
              </div>
            </el-form-item>
          </div>
        </div>
      </el-form>
      <empty-page v-if="isEmpty&&!isLoading"></empty-page>
    </div>
  </div>
</template>

<script>
import TwoTitle from '@/components/TwoTitle'
import EmptyPage from '@/components/EmptyPage'
import tree from '@/utils/dataParse.js'
import {validateEmail} from '@/utils/validate'
export default {
  name: 'EmployeeDetail',
  components: {
    TwoTitle,
    EmptyPage
  },
  data () {
    return {
      isLoading: false, // 数据加载中
      startWatch: false, // 是否开始监听页面数据变化 统一
      isEmpty: false, // 是否为空数据
      isSelectWorkShop: false, // 是否禁止选择班组
      // 表单验证规则
      rules: {
        number: [
          {required: true, message: '请输入人员编号', trigger: 'blur'},
        ],
        name: [
          {required: true, message: '请输入人员名称', trigger: 'blur'},
        ],
        factoryId: [
          {required: true, message: '缺少工厂信息', trigger: 'blur'}
        ],
        workshopId: [
          {required: true, message: '缺少车间信息', trigger: 'blur'}
        ],
        workgroupId: [
          {required: true, message: '请选择班组名称', trigger: 'blur'}
        ],
        email: [
          {validator: validateEmail, message: '请输入正确的邮箱地址', trigger: 'blur'}
        ],
        remarks: [
          {max: 255, message: '备注长度不能超过255字符', trigger: 'blur'}
        ]
      }
    }
  },
  computed: {
    // 详情数据
    detailData () {
      return this.$store.state.employee.detailData
    },
    // 树形数据
    treeList () {
      return this.$store.state.treeList
    },
    // 工厂id
    factoryId() {
      return this.$store.state.userInfo.factoryId || ''
    },
    // 车间id
    workshopId() {
      return this.$store.state.userInfo.workshopId || ''
    },
    // 车间下拉列表
    workshop () {
      return tree.getChildren(this.treeList, this.detailData.factoryId)
    },
    // 班组下拉列表
    workgroup () {
      return tree.getChildren(this.workshop, this.detailData.workshopId)
    },
    // 计算工龄
    workTime () {
      if (this.detailData.workingDate) {
        let oneYear = 365 * 24 * 60 * 60 * 1000
        let yearsUnix = new Date().getTime() - new Date(this.detailData.workingDate).getTime()
        if (yearsUnix >= oneYear) {
          return '工龄：' + String(Math.floor(yearsUnix / oneYear)) + ' 年'
        } else {
          return '工龄：0 年'
        }
      }
    },
    // 字典获取的性别下拉列表
    genderType() {
      return this.$store.state.dict.sex.labels || []
    }
  },
  mounted() {
    this.refresh()
  },
  methods: {
    /**
     * 初始化页面数据
     */
    refresh() {
      this.isLoading = true
      this.startWatch = false
      Promise.all([this.getDetail(), this.getTreeList(), this.getGender()]).then(() => {
        this.isLoading = false
      }).catch(() => {
        this.isLoading = false
      })
    },
    /**
     * 初始化——详情数据
     */
    getDetail() {
      let id = this.$route.query.id
      let postData = {
        method: 'get',
        url: 'a/staff/staff/get/' + id,
        module: 'employee',
        state: 'detailData'
      }
      if (!id) { postData.clean = true }
      return this.$store.dispatch('saveData', postData).then((res) => {
        this.startWatch = true
        if (res.workgroupId) this.isSelectWorkShop = true
        if (id && !res) { this.isEmpty = true }
      }).catch(() => {
        this.isEmpty = true
      })
    },
    /**
     * 初始化——树形结构数据
     */
    getTreeList() {
      return this.$store.dispatch('getTreeList')
    },
    /**
     * 获取性别字典数据
     * */
    getGender() {
      return this.$store.dispatch('saveData', {
        method: 'get',
        url: 'a/staff/staff/dict/sex',
        module: 'employee',
        state: 'genderList'
      })
    },
    /**
     * 选择工厂并重置车间列表
     * @param value
     * @param a
     * @private
     */
    factorySelect (value, a) {
      this.$store.dispatch('setSecondValue', '')
    },
    /**
     * 选择车间并重置班组列表
     */
    workshopSelect () {
      this.$store.dispatch('setThirdValue', '')
    },
    /**
     * 出生日期
     */
    getPickerOptions1(min) {
      let self = this
      return {
        disabledDate(time) {
          if (self.moment().isBefore(min) || !min) {
            return time.getTime() > self.$startTimeStamp(window.serverTime)
          } else {
            return time.getTime() > self.$startTimeStamp(min)
          }
        }
      }
    },
    /**
     * 参工时间
     */
    getPickerOptions2(min) {
      let self = this
      return {
        disabledDate(time) {
          if (self.detailData.birthday) {
            return time.getTime() < self.$startTimeStamp(min)
          } else {
            return time.getTime() > self.$startTimeStamp()
          }
        }
      }
    },
    /**
     * 获取班组名称
     * @param ids 下拉选择框所选id list
     * @param treeList 下拉选择框选项 list
     */
    getNameList(ids, treeList) {
      let result = []
      ids.forEach((item) => {
        let obj = treeList.find((value) => item === value.id)
        if (obj) result.push(obj.text)
      })
      return result.join(',')
    },
    /**
     * 保存数据
     */
    save() {
      if (this.saveState === true) return
      let detail = JSON.parse(JSON.stringify(this.detailData))
      detail.workgroupName = this.getNameList([detail.workgroupId], this.workgroup)
      this.$refs['listForm'].validate((valid) => {
        if (valid) {
          this.$store.commit('SetSaveState', true)
          let postData = {
            method: 'post',
            url: 'a/staff/staff/save',
            module: 'employee',
            data: detail,
            noCommit: true
          }
          this.$store.dispatch('saveData', postData).then(() => {
            this.saveSuccess()
          }).catch(() => {
            this.$store.commit('SetSaveState', false)
          })
        }
      })
    },
    /**
     * 保存成功回调
     */
    saveSuccess() {
      this.$message.success({
        message: '保存成功',
        duration: 500,
        center: true,
        onClose: () => {
          this.$store.commit('SetHasDetailChange', false) // 保存成功时需要将页面变化标记重置回false
          this.$store.dispatch('delCurrentViews', this.$route).then(() => {
            this.$store.commit('SetSaveState', false)
            this.$router.push('/employee')
            this.$store.commit('SetRefresh', true)
          })
        }
      })
    },
    /**
     * 取消关闭页面
     */
    cancel() {
      this.backToList().then(() => {
        this.$store.dispatch('delCurrentViews', this.$route).then(() => {
          this.$router.push('/employee')
        }
        )
      })
    }
  },
  watch: {
    detailData: {
      // 当前页面数据变化总是会被监听到，我们只需要在我们想要开始监听startWatch的时候判断当前页面是否有变化
      handler() {
        if (this.startWatch) {
          this.$store.commit('SetHasDetailChange', true)
        } else {
          this.$store.commit('SetHasDetailChange', false)
        }
      },
      deep: true
    }
  }
}
</script>

<style lang="less">
</style>
